<template>
  <el-container class="container-box">
    <el-container class="container-left">
      <el-main class="container-content">
        <div class="container-header-form">
          <el-form size="default" :inline="true" label-position="left" label-width="">
            <el-form-item label="提交人" class="container-header-form-item">
              <el-select-v2 class="container-header-form-item-select-v2" size="default" v-model="userId"
                @clear="handleClear" :options="getusers" filterable :clearable="!!userId" placeholder="可输入名称查询">
              </el-select-v2>
            </el-form-item>
            <el-form-item label="评测时间" class="container-header-form-item">
              <el-date-picker v-model="formdate" type="daterange" unlink-panels range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" size="default" />
            </el-form-item>
            <el-form-item label="题目ID" class="container-header-form-item">
              <el-input v-model.number="questionid" placeholder="请输入题目ID" style="width: 180px" clearable></el-input>
            </el-form-item>
            <el-form-item label="题单ID" class="container-header-form-item">
              <el-input v-model.number="questionbankid" placeholder="请输入题单ID" style="width: 180px" clearable></el-input>
            </el-form-item>
            <el-form-item class="container-header-form-item">
              <el-button class="container-header-form-search-btn" type="primary" size="default"
                @click="start">查询</el-button>
              <el-button class="container-header-form-search-btn" type="primary" v-if="Number(teamInfo.grade) > 1"
                @click="() => download()">下载</el-button>
              <el-button class="container-header-form-search-btn" type="primary" v-if="Number(teamInfo.grade) > 1"
                @click="() => download(true)">下载全部</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table stripe class="" v-loading="loading" :row-class-name="rowClassName" :data="userquestion"
          @row-click="clickRow">
          <template v-slot:empty>
            <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
          </template>
          <el-table-column prop="createdAt" label="提交时间" :formatter="({ createdAt }) => TimeYH(createdAt)"
            show-overflow-tooltip width="150">
          </el-table-column>
          <el-table-column prop="type" label="题型" width="60"></el-table-column>
          <el-table-column prop="questionbankid" label="题单ID" width="80"></el-table-column>
          <el-table-column prop="questionid" label="题目ID" width="80">
            <template #default="{ row }">
              <router-link v-slot="{ href }" custom :to="{ name: '题目', params: { ID: row.questionid }, }">
                <el-link target="_blank" :href="href">{{ row.questionid }}</el-link>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column prop="question.name" label="题目" show-overflow-tooltip width=""></el-table-column>
          <el-table-column prop="user.name" label="提交人" show-overflow-tooltip width="110">
            <template #default="{ row }">
              <router-link v-slot="{ href }" custom :to="{ name: '用户', query: { userid: row.userid }, }">
                <el-link target="_blank" :href="href"> {{ row.user.name }}
                </el-link>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column prop="resultdata" label="评测结果" width="">
            <template #default="{ row }">
              <div class="submission-table">
                <span v-if="row.type === '代码'">
                  <el-tag class="question-intable-label" effect="dark"
                    v-text="ALLTYPE[row.resultdata ? row.resultdata : 'WT'][1]"
                    :class="'bg-' + ALLTYPE[row.resultdata ? row.resultdata : 'WT'][1]">
                  </el-tag>
                </span>
                <span v-else>{{ row.resultdata ? row.resultdata : '错误' }}</span>
                <span v-if="Array.isArray(row.resultdataarr)">
                  <span :style="{ display: 'inline-block' }" v-for="(v, key) in acgroup(row.resultdataarr)"
                    :key="'a_' + key">&nbsp;
                    <span effect="dark" :class="ALLTYPE[v[0]][1]">{{ v[0] }}:{{ v[1] }}</span>
                  </span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="runParam" label="运行参数" :formatter="getRunParam" width="120"></el-table-column>
        </el-table>
        <el-pagination class="pager" size="default" :page-size="limit" :total="totalCount" @current-change="changePage"
          layout="total,prev, pager, next" :current-page="Math.floor(offset / limit) + 1">
        </el-pagination>
      </el-main>
    </el-container>
    <el-aside class="container-aside">
      <el-scrollbar>
        <div class="container-aside-content">
          <CaseDetail v-if="showCaseDetail" :row="rowData"></CaseDetail>
          <TeamData v-else :formdata="{ userId: userId, times, showTeamData }"></TeamData>
        </div>
      </el-scrollbar>
    </el-aside>
  </el-container>
</template>

<script setup lang="ts">
import { ElMessage, dayjs } from "element-plus";
import moment from "moment";
import { countBy, pairs } from "underscore";
import { computed, inject, onMounted, onUnmounted, ref, watch } from "vue";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { Iobj, asyncgetteam, asyncselectteamselectuser, asyncselectuserquestion } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { getExceltodownload } from "../../../util/excel";
import { ALLTYPE } from "@/util/jianchatime";
import { TimeYH, shortcuts } from "../../../util/time";
import CaseDetail from "./caseDetail.vue";
import TeamData from "./teamData.vue";

const defaultYear = new Date("2000")
const dayMs = 3600 * 1000 * 24
const yearMs = dayMs * 365


const route = useRoute();
const router = useRouter();
const headnavdialogVisible = inject("headnavdialogVisible", () => { });

// 路由参数
const routeQuery = computed(() => {
  return route.query;
});
// ?????????????
const isad = computed(() => {
  return Number(routeQuery.value.isad) || 0;
});
// 表格数据
const userquestion = ref<Studycodemodel.Iuserquestion[]>([]);
const totalCount = ref(0);
// 排序
const order = computed(() => {
  return routeQuery.value.order || "ID";
});
// 
const offset = ref(0)
const limit = ref(30)

const store = useStore(Storekey);
// 当前登录用户
const user = computed(() => {
  return store.state.user;
});
const teamid = computed(() => {
  return user.value?.teamid;
});
const teamInfo = ref<Studycodemodel.Iteam>({})
// 搜索条件
const loading = ref(false)
const questionid = ref<number | null>();
const questionbankid = ref<number>();
const userId = ref<number | undefined>(0);
const showTeamData = ref(false)

const formdate = ref<[Date, Date]>() // [new Date(Date.now() - yearMs), new Date()]
const times = computed<[string, string]>(() => {
  let tmp = []
  if (!formdate.value) { // 不能设为空值 默认2000年-查全部
    tmp = [defaultYear, new Date()]
  } else {
    tmp = formdate.value
  }
  return [dayjs(tmp[0]).format('YYYY-MM-DD 00:00:00'), dayjs(tmp[1]).format('YYYY-MM-DD 23:59:59')]
});

const teamUsers = ref<Studycodemodel.Iteamuser[]>([])
const getusers = computed(() => {
  const isTeamUser = teamUsers.value.find(e => (e.user?.ID === user.value?.ID))
  if (!isTeamUser) {
    return [
      { value: 0, label: '全部成员' },
      ...teamUsers.value.map(e => ({ value: e.user?.ID, label: e.user?.name }))
    ]
  }
  return [
    { value: 0, label: '全部成员' },
    // 登录者排第二
    { value: user.value?.ID, label: user.value?.name },
    ...teamUsers.value.filter(e => (e.user?.ID !== user.value?.ID)).map(e => ({ value: e.user?.ID, label: e.user?.name }))
  ]
})
const ID = ref<number[]>([])

const handleClear = () => {
  // 如果当前不是 "全部"，则清空时设置为0（表示 "全部"）
  // if (userId.value) {
  userId.value = 0;
  // }
}
// 监听 userId 的变化，更新路由参数
watch(userId, newUserId => {
  start();
  // if (newUserId) {
  router.replace({ query: { ...route.query, userid: newUserId } });
  // }
  // caseDetail-切换右侧图表
  if (showCaseDetail.value) {
    showCaseDetail.value = false
    rowData.value = {}
  }
});
watch(times, (v) => {
  start();
});
watch(questionid, (v) => {
  start();
});
watch(questionbankid, (v) => {
  start();
});

// caseDetail
const rowData = ref({});
const showCaseDetail = ref(false)
function clickRow(row: any, column: any, event: Event): void {
  if (rowData.value !== row) {
    rowData.value = row
    showCaseDetail.value = true
    return
  }
  showCaseDetail.value = false
  rowData.value = {}
}
function rowClassName({ row, rowIndex }: { row: any, rowIndex: number }): string {
  let className = 'cursor-pointer'
  if (rowData.value == row) {
    className = 'highlight-row cursor-pointer'; // 
  }
  return className;
};

// 
onMounted(async () => {
  if (!user.value) {
    headnavdialogVisible();
    return;
  }
  if (!teamid.value) {
    console.log("task index teamid is null")
    return
  }
  await init()
  // 搜索
  start()
})
// 监听团队切换
watch(() => teamid.value, async (o, n) => {
  if (o !== n) {
    await init()
    start();
  }
})
async function init() {
  // getteam 获取团队信息
  teamInfo.value = await asyncgetteam({ ID: teamid.value as number });
  teamUsers.value = await asyncselectteamselectuser({ teamid: teamid.value });
  showTeamData.value = true

  questionid.value = Number(routeQuery.value.questionid) || null;
  questionbankid.value = Number(routeQuery.value.questionbankid) || undefined;
  // 校验uid和团队的关系  
  if (routeQuery.value.userid) {
    const inTeam = getusers.value.map(e => e.value).includes(Number(routeQuery.value.userid));
    if (inTeam) {
      userId.value = Number(routeQuery.value.userid);
    }
  }
}
async function start() {
  if (!isad.value && [questionid.value, questionbankid.value, teamid.value].every((e) => !e)) {
    ElMessage.error("请最少添加一种搜索条件");
    return;
  }

  // 组装查询语句
  const userid = userId.value;
  const formquery: Iobj<Studycodemodel.Iuserquestion> = {
    _limit: limit.value,
    _offset: offset.value,
    // type: '代码',
    _order: 'ID',
    _sortable: 'DESC'
  };
  if (userid) {
    formquery.userid = userid;
  } else {
    formquery.userid = getusers.value.map(e => e.value).filter(e => e)
  }
  if (ID.value.length) {
    formquery.ID = ID.value
  }
  if (times.value && times.value[0] && times.value[1]) {
    formquery.createdAt = { lt: times.value[1], gt: times.value[0], };
  }
  if (questionbankid.value) {
    formquery.questionbankid = questionbankid.value;
  }
  if (questionid.value) {
    Object.assign(formquery, { questionid: questionid.value, });
  }
  loading.value = true;
  const { rows, count } = await asyncselectuserquestion(Object.assign(formquery));
  loading.value = false;
  totalCount.value = count;
  userquestion.value = rows
}
onUnmounted(() => {
  window.onresize = () => { };
});

function acgroup(data?: Array<keyof Studycodemodel.IALLTYPE>) {
  if (Array.isArray(data)) {
    const c = countBy(data, (a) => {
      return a
    })
    return pairs(c)
  }
  return []
}
function getRunParam(row: Studycodemodel.Iuserquestion): string {
  if (row.type !== '代码') return '无'
  let gccoptimize = row.gccoptimize ? `${row.gccoptimize}/` : "";
  let rowLanguage = row.language?.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
  rowLanguage = rowLanguage !== 'Cpp' ? rowLanguage : 'C++'
  return gccoptimize + rowLanguage
}

const height = ref(window.innerHeight - 74);
function onresize(e: UIEvent) {
  height.value = window.innerHeight - 74;
}
window.onresize = onresize;

onBeforeRouteUpdate(() => {
  // questionid.value = Number(routeQuery.value.questionid) || null;
  // questionbankid.value =
  //   (routeQuery.value.questionbankid as unknown as number) || undefined;
});

function tableRowClassName({ row, rowIndex }: any) {
  if (rowIndex % 2 === 1) {
    return "warning-row";
  } else {
    return "success-row";
  }
}

// 翻页
function changePage(r: number) {
  offset.value = (r - 1) * limit.value;
  start()
}

function down(row: Studycodemodel.Iuserquestion) {
  const { context, language } = row;
  if (context) {
    let t = ".cpp";
    if ("c" === language) {
      t = ".c";
    }
    if ("python" === language) {
      t = ".py";
    }
    const bo = new File(
      [context],
      row.user?.name + "_" + row.question?.name + t,
      {
        type: "text/plain",
      }
    );
    var a = document.createElement("a");
    a.download = row.user?.name + "_" + row.question?.name + t;
    a.href = URL.createObjectURL(bo);
    a.click();
  } else {
    ElMessage.error("代码为空");
  }
}

// 
async function download(b?: boolean) {
  const data1: string[][] = [
    ["用户", "题目ID", "题单ID", "答题时间", "题目名称", "AC", "代码"],
  ];
  if (!b) {
    userquestion.value.forEach((e) => {
      let {
        user,
        question,
        questionbankid,
        questionid,
        info,
        context,
        createdAt,
      } = e;
      const contextarr = []
      for (let v = 0; v < String(context).length; v = v + 30000) {
        if (v === 0 && String(context).length > 30000) {
          contextarr.push('本次提交代码过长超出Excel单元格限制，请拼接后续单元格组成代码')
        }
        contextarr.push(String(context).slice(v, v + 30000))
      }
      data1.push([
        String(user?.name),
        String(questionid),
        String(questionbankid),
        TimeYH(createdAt),
        String(question?.name),
        e.resultdata ? e.resultdata : '',
        ...contextarr,
      ]);
    });
  } else {
    const userid = userId.value;
    const formquery: Iobj<Studycodemodel.Iuserquestion> = {
      _limit: totalCount.value,
      _offset: 0,
      _order: 'ID',
      _sortable: 'DESC'
    };
    if (userid) {
      formquery.userid = userid;
    } else {
      formquery.userid = getusers.value.map(e => e.value).filter(e => e)
    }
    if (times.value && times.value[0] && times.value[1]) {
      formquery.createdAt = {
        lt: times.value[1],
        gt: times.value[0],
      };
    }
    if (questionbankid.value) {
      formquery.questionbankid = questionbankid.value;
    }
    if (questionid.value) {
      Object.assign(formquery, {
        questionid: questionid.value,
      });
    }
    const { rows, count } = await asyncselectuserquestion(
      Object.assign(formquery)
    );
    rows
      .forEach((e) => {
        let {
          user,
          question,
          questionbankid,
          questionid,
          info,
          context,
          createdAt,
        } = e;
        let { result } = e;
        const contextarr = []
        for (let v = 0; v < String(context).length; v = v + 30000) {
          if (v === 0 && String(context).length > 30000) {
            contextarr.push('本次提交代码过长超出Excel单元格限制，请拼接后续单元格组成代码')
          }
          contextarr.push(String(context).slice(v, v + 30000))
        }
        data1.push([
          String(user?.name),
          String(questionid),
          String(questionbankid),
          TimeYH(createdAt),
          String(question?.name),
          e.resultdata ? e.resultdata : '',
          ...contextarr,
        ]);
      });
  }
  if (data1.length > 1) {
    const team = teamid.value;
    const startDate = times.value[0] ? moment(times.value[0]).format("YYYYMMDD") : ""
    const endDate = times.value[1] ? moment(times.value[1]).format("YYYYMMDD") : ""
    const name = `${teamInfo.value?.name ? teamInfo.value.name : "学生日志"}_${startDate}-${endDate}`;
    getExceltodownload(data1, name);
  }
}
</script>

<style scoped>
.container-box {
  padding: var(--container-margin) 5% 0;
  margin: var(--container-margin) 0rem 0 0rem;
  /* 外边距 */
  --container-margin: 20px;
  --container-header-height: 20vh;
  --container-bg-color: #fff;
}

.container-left {
  margin-right: var(--container-margin);
}

.container-header {
  height: var(--container-header-height);
  min-height: var(--container-header-height);
  width: 100%;
  padding: var(--container-margin);
  background: var(--container-bg-color);
}

.container-header-form {
  /* margin-bottom: 20px; */
}

.container-header-form-item-select-v2 {
  width: auto;
  min-width: 200px;
  /* 根据需要调整 */
  display: inline-block;
  white-space: nowrap;
}

.container-header-form-item {
  font-weight: 700;
  --color-43: #000;
  text-align: left;
}

.container-header-form-item .el-button.is-text {
  border-width: 1px;
}

.container-header-form-item .el-button--default:active {
  border-color: transparent
}

.container-content {
  /* margin-top: var(--container-margin); */
  background: var(--container-bg-color);
  padding: var(--container-margin);
  min-width: 100%;
}

.submission-table .el-tag {
  width: 90px;
  border-radius: 4px;
  border: none;
}

.container-content .pager {
  margin: var(--container-margin);
  margin-right: 0;
  margin-bottom: 0;
  float: right;
}

.container-aside {
  min-width: 30%;
  background: var(--container-bg-color);
  /* max-height: 162vh; */
}

.container-aside-content {
  padding: 0 var(--container-margin);
}
</style>
